package com.itheima.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class SmsUtil {

    // 产品名称: 云通信短信服务API产品, 开发者无需替换
    static final String product = "Dysmsapi";
    static final String domain = "dysmsapi.aliyuncs.com";

    // 替换为你的 AccessKey ID 和 Secret
    private static final String accessKeyId = "yourAccessKeyId";
    private static final String accessKeySecret = "yourAccessKeySecret";

    // 存储验证码（实际项目中建议使用 Redis 或数据库）
    private static Map<String, VerificationCode> verificationCodes = new HashMap<>();

    // 验证码过期时间（毫秒），默认5分钟
    private static final long DEFAULT_EXPIRE_TIME = 5 * 60 * 1000;

    /**
     * 验证码存储结构体
     */
    public static class VerificationCode {
        String code;
        long timestamp;

        public VerificationCode(String code) {
            this.code = code;
            this.timestamp = System.currentTimeMillis();
        }

        public boolean isExpired(long currentTime, long expireTimeMillis) {
            return (currentTime - timestamp) > expireTimeMillis;
        }
    }

    /**
     * 初始化短信客户端
     */
    private static IAcsClient createAcsClient() throws ClientException {
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", product, domain);
        return new DefaultAcsClient(profile);
    }

    /**
     * 发送短信验证码
     *
     * @param phoneNumber 手机号
     * @param signName    短信签名
     * @param templateCode 模板CODE
     * @return 是否发送成功
     */
    public static boolean sendVerificationCode(String phoneNumber, String signName, String templateCode) {
        Random random = new Random();
        String code = String.format("%06d", random.nextInt(999999));

        // 存储验证码
        verificationCodes.put(phoneNumber, new VerificationCode(code));

        try {
            IAcsClient acsClient = createAcsClient();

            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phoneNumber);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);

            // 构造模板参数 JSON 字符串
            String templateParam = String.format("{\"code\":\"%s\"}", code);
            request.setTemplateParam(templateParam);

            // 发送短信
            SendSmsResponse response = acsClient.getAcsResponse(request);

            if ("OK".equals(response.getCode())) {
                System.out.println("验证码已发送至：" + phoneNumber);
                return true;
            } else {
                System.err.println("发送失败，错误信息：" + response.getMessage());
                return false;
            }

        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 验证用户输入的验证码是否正确
     *
     * @param phoneNumber   手机号
     * @param inputCode     用户输入的验证码
     * @param expireTimeMillis 验证码有效时间（毫秒）
     * @return 是否验证通过
     */
    public static boolean verifyVerificationCode(String phoneNumber, String inputCode, long expireTimeMillis) {
        VerificationCode storedCode = verificationCodes.get(phoneNumber);
        if (storedCode == null || storedCode.isExpired(System.currentTimeMillis(), expireTimeMillis)) {
            return false; // 验证码不存在或已过期
        }
        return storedCode.code.equals(inputCode); // 匹配验证码
    }

    /**
     * 使用默认过期时间验证验证码（5分钟）
     */
    public static boolean verifyVerificationCode(String phoneNumber, String inputCode) {
        return verifyVerificationCode(phoneNumber, inputCode, DEFAULT_EXPIRE_TIME);
    }

    // --------------------------
    // 示例 main 方法测试
    // --------------------------
    public static void main(String[] args) {
        String phoneNumber = "13800001111"; // 替换为测试手机号
        String signName = "阿里云短信测试";   // 替换为你审核通过的签名
        String templateCode = "SMS_123456789"; // 替换为你审核通过的模板CODE

        // 发送验证码
        boolean sent = sendVerificationCode(phoneNumber, signName, templateCode);
        if (!sent) {
            System.out.println("验证码发送失败");
            return;
        }

        // 模拟用户输入验证码（实际应由前端传入）
        String userInputCode = "123456"; // 测试用，替换成真实用户输入

        // 验证验证码
        boolean result = verifyVerificationCode(phoneNumber, userInputCode);
        if (result) {
            System.out.println("验证码正确！");
        } else {
            System.out.println("验证码错误或已过期！");
        }
    }
}